package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.truck;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class QueueHandlingZxBu {
    @Autowired
    private ICIcCardsInfoService iCIcCardsInfoService;
    @Autowired
    private ICCompanysService iCCompanysService;
    @Autowired
    private ICOrderDetailService iCOrderDetailService;
    @Autowired
    private ICSysCfgService iCSysCfgService;
    @Autowired
    private ICProductsInfoService iCProductsInfoService;
    @Autowired
    private ICPdtClassService iCPdtClassService;
    @Autowired
    private ICPdtsAuthService iCPdtsAuthService;
    @Autowired
    private ICPdtPlanExService iCPdtPlanExService;
    @Autowired
    private ICWeightSheetsService iCWeightSheetsService;
    @Autowired
    private ICTrucksService iCTrucksService;
    @Autowired
    private ITGypsumPlanService iTGypsumPlanService;


//    余额是否充足

    public boolean balanceIsEnough(String plant, String co,String chiCo, String cardinfTruckTypeValue, String cardinfTruckPwd) {
        boolean flag = false;
        QueryWrapper<CProductsInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("PDTINF_PDT", cardinfTruckTypeValue);
        queryWrapper2.ne("PDTINF_DELETED", 1);
        CProductsInfo cProductsInfo = iCProductsInfoService.getOne(queryWrapper2);

        QueryWrapper<COrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ORDETAIL_CO", co);
        queryWrapper1.eq("ORDETAIL_CHICO", chiCo);
        queryWrapper1.eq("ORDETAIL_SUB_ID", cProductsInfo.getPdtinfSubjectId());
        queryWrapper1.eq("ORDETAIL_DELETED", 0);
        queryWrapper1.eq("DATA_FROM", plant);
//        余额ORDETAIL_REMAIN_NUM大于0,这里考虑了如果余额账户没建立的情况，我们就把余额先置为0，交给下面的余额判断逻辑去处理
        COrderDetail cOrderDetail = iCOrderDetailService.getOne(queryWrapper1);
        if (cOrderDetail == null || cOrderDetail.getOrdetailRemainNum() == null) {
            if (cOrderDetail != null) {
                cOrderDetail.setOrdetailRemainNum(new BigDecimal(0));
            }else {
                cOrderDetail = new COrderDetail();
                cOrderDetail.setOrdetailRemainNum(new BigDecimal(0));
            }
        }

        QueryWrapper<CPdtsAuth> queryWrapper6 = new QueryWrapper<>();
        queryWrapper6.eq("PDTSAUTH_CO", co);
        queryWrapper6.eq("PDTSAUTH_CHICO",chiCo);
        queryWrapper6.eq("PDTSAUTH_DELETED", 0);
        queryWrapper6.eq("PDTSAUTH_PDT", cardinfTruckTypeValue);
        CPdtsAuth cPdtsAuth = iCPdtsAuthService.getOne(queryWrapper6);
        QueryWrapper<CWeightSheets> eightSheetsQueryWrapper = new QueryWrapper<>();
        eightSheetsQueryWrapper.eq("WEISHT_TRUCKNO", cardinfTruckPwd);
        eightSheetsQueryWrapper.eq("WEISHT_DELETED", 0);
        eightSheetsQueryWrapper.ne("WEISHT_NET_WGHT", 0);
        eightSheetsQueryWrapper.eq("DATA_FROM", plant);
        eightSheetsQueryWrapper.orderByDesc("WEISHT_FULL_TM");
        eightSheetsQueryWrapper.last("limit 3");
        List<CWeightSheets> eightSheets = iCWeightSheetsService.list(eightSheetsQueryWrapper);
        BigDecimal netWght = new BigDecimal(0);
        if (eightSheets.size()==0) {
            QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
            cTrucksQueryWrapper.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
            cTrucksQueryWrapper.eq("TRUCKS_DELETED", 0);
            cTrucksQueryWrapper.eq("DATA_FROM", plant);
            CTrucks cTrucks2 = iCTrucksService.getOne(cTrucksQueryWrapper);
            if (cTrucks2 != null && cTrucks2.getTrucksRefNet()!=null) {
                netWght = netWght.add(cTrucks2.getTrucksRefNet());
            } else {
                //            系统默认的参考净重
                QueryWrapper<CSysCfg> cSysCfgQueryWrapper2 = new QueryWrapper<>();
                cSysCfgQueryWrapper2.eq("SYSCFG_ITEM_NAME", "TempTruckDefRefNet");
                cSysCfgQueryWrapper2.eq("DATA_FROM", plant);
                CSysCfg cSysCfg2 = iCSysCfgService.getOne(cSysCfgQueryWrapper2);
                netWght = netWght.add(cSysCfg2.getSyscfgLongValue());
            }
        } else {
            for (CWeightSheets cWeightSheet : eightSheets) {
                netWght = netWght.add(cWeightSheet.getWeishtNetWght());
            }
            netWght = netWght.divide(new BigDecimal(eightSheets.size()), 2, RoundingMode.HALF_UP);
        }
        Map<String, Double> map = creditIsEnough(plant,co,chiCo,cProductsInfo.getPdtinfSubjectId());
        if (map.get("ok") == 1.0) {
            BigDecimal remainNum = new BigDecimal(cOrderDetail.getOrdetailRemainNum().toString());
            BigDecimal preLic = new BigDecimal(map.get("preLic").toString());
            BigDecimal netWeight = new BigDecimal(netWght.toString());
            BigDecimal pdtsPrice = new BigDecimal(cPdtsAuth.getPdtsauthPrice().toString());
            BigDecimal result = remainNum.add(preLic).subtract(netWeight.multiply(pdtsPrice));
            if (result.compareTo(BigDecimal.ZERO) > 0) {
                flag = true;
            }
        } else if (map.get("ok") == 0.0){
            BigDecimal remainNum = new BigDecimal(cOrderDetail.getOrdetailRemainNum().toString());
            BigDecimal netWeight = new BigDecimal(netWght.toString());
            BigDecimal pdtsPrice = new BigDecimal(cPdtsAuth.getPdtsauthPrice().toString());
            BigDecimal result = remainNum.subtract(netWeight.multiply(pdtsPrice));
            if (result.compareTo(BigDecimal.ZERO) > 0) {
                flag = true;
            }

        }else if (map.get("ok") == 2.0) {
            BigDecimal remainNum = new BigDecimal(cOrderDetail.getOrdetailRemainNum().toString());
            BigDecimal netWeight = new BigDecimal(netWght.toString());
            BigDecimal pdtsPrice = new BigDecimal(cPdtsAuth.getPdtsauthPrice().toString());
            BigDecimal result = remainNum.subtract(netWeight.multiply(pdtsPrice));
            if (result.compareTo(BigDecimal.ZERO) > 0) {
                flag = true;
            }
        }
        return flag;
    }

    //    判断是否开启授信额度，额度是否充足
    public Map<String, Double> creditIsEnough(String plant,String co,String chiCo,String pdtinfSubjectId) {
        Map<String, Double> map = new HashMap<>();
        map.put("preLic", 0.0);
        map.put("ok", 0.0);
        QueryWrapper<CSysCfg> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("SYSCFG_ITEM_NAME", "CreditLineEn");
        queryWrapper2.eq("DATA_FROM", plant);
        CSysCfg cSysCfg = iCSysCfgService.getOne(queryWrapper2);
//        检查SYSCFG_LONG_VALUE不为1就返回false
        if (Double.parseDouble(cSysCfg.getSyscfgLongValue().toString()) != 1) {
            return map;
        }
        QueryWrapper<COrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ORDETAIL_CO", co);
        queryWrapper1.eq("ORDETAIL_CHICO",chiCo);
        queryWrapper1.eq("ORDETAIL_SUB_ID",pdtinfSubjectId);
        queryWrapper1.ne("ORDETAIL_DELETED", 1);
        queryWrapper1.eq("DATA_FROM", plant);
//        余额ORDETAIL_PRE_LIC大于0
        COrderDetail cOrderDetail = iCOrderDetailService.getOne(queryWrapper1);
        if (cOrderDetail == null || cOrderDetail.getOrdetailPreLic() ==null) {
            map.put("ok",2.0);
            return map;
        } else {
            map.put("preLic", Double.parseDouble(cOrderDetail.getOrdetailPreLic().toString()));
            map.put("ok", 1.0);
            return map;
        }
    }


    //    判断是否到达品种的下限余量
    public Map<String, Object> isLowerLimit(String plant,String co,String chiCo, String cardinfTruckTypeValue) {
        Map<String, Object> map = new HashMap<>();
        map.put("limit", "0.0");
        map.put("ok", "0.0");
        String subjectName = "" ;
        map.put("SubjectName",subjectName);
//        判断品种是粉煤灰还是石膏还是渣，还是其他
        QueryWrapper<CProductsInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("PDTINF_PDT", cardinfTruckTypeValue);
        queryWrapper1.eq("PDTINF_DELETED", 0);
        CProductsInfo cProductsInfo = iCProductsInfoService.getOne(queryWrapper1);
        QueryWrapper<CPdtClass> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("PDTCLASS_ID", cProductsInfo.getPdtinfClass());
        queryWrapper2.eq("PDTCLASS_DELETED", 0);
        CPdtClass cPdtClass = iCPdtClassService.getOne(queryWrapper2);
//        查出余额
        QueryWrapper<COrderDetail> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("ORDETAIL_CO", co);
        queryWrapper3.eq("ORDETAIL_CHICO", chiCo);
//        queryWrapper3.eq("ORDETAIL_SUB_ID", cProductsInfo.getPdtinfSubjectId());
        queryWrapper3.ne("ORDETAIL_DELETED", 1);
        queryWrapper3.eq("DATA_FROM", plant);
        List<COrderDetail> cOrderDetails = iCOrderDetailService.list(queryWrapper3);
        if (cOrderDetails.size()==0) {
            return map;
        }
        for (COrderDetail cOrderDetail:cOrderDetails) {
            CCompanys cCompanys = iCCompanysService.getById(cOrderDetail.getOrdetailSubId());
            if (cCompanys!=null) {
                 subjectName = cCompanys.getCpyCo() + "." + cCompanys.getCpyChico();
                map.put("SubjectName",subjectName);
            }
            BigDecimal ordetailPreLic = BigDecimal.valueOf(0);
            if (cOrderDetail != null && cOrderDetail.getOrdetailPreLic() != null) {
                ordetailPreLic = cOrderDetail.getOrdetailPreLic();
            }
//        查出是否开启授信额度,和授信额度是多少
            QueryWrapper<CSysCfg> queryWrapper6 = new QueryWrapper<>();
            queryWrapper6.eq("SYSCFG_ITEM_NAME", "CreditLineEn");
            queryWrapper6.eq("DATA_FROM", plant);
            CSysCfg cSysCfg1 = iCSysCfgService.getOne(queryWrapper6);
            boolean CreditLineEn = false;
            if (cSysCfg1 != null) {
                if (cSysCfg1.getSyscfgLongValue().compareTo(BigDecimal.valueOf(1)) == 0) {
                    CreditLineEn = true;
                }
            }
            if (Objects.equals(cPdtClass.getPdtclassClass(), "粉煤灰")) {
                QueryWrapper<CSysCfg> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("SYSCFG_ITEM_NAME", "RemainLimit_Powder");
                queryWrapper4.eq("DATA_FROM", plant);
                CSysCfg cSysCfg = iCSysCfgService.getOne(queryWrapper4);
                if (Double.parseDouble(cSysCfg.getSyscfgLongValue().toString()) > 0) {
                    QueryWrapper<CPdtsAuth> queryWrapper5 = new QueryWrapper<>();
                    queryWrapper5.eq("PDTSAUTH_CO", co);
                    queryWrapper5.eq("PDTSAUTH_CHICO", chiCo);
                    queryWrapper5.eq("PDTSAUTH_DELETED", 0);
                    queryWrapper5.eq("PDTSAUTH_PDT", cardinfTruckTypeValue);
                    CPdtsAuth cPdtsAuth = iCPdtsAuthService.getOne(queryWrapper5);
//            如果cSysCfg的值不为0就判断cSysCfg的值乘以cPdtsAuth里的价格判断是否大于余额,如果if (Integer.parseInt(cSysCfg1.getSyscfgLongValue().toString()) == 1) 就判断是否大于余额加上授信额度
                    if (CreditLineEn) {
                        if (cOrderDetail.getOrdetailRemainNum().compareTo(cPdtsAuth.getPdtsauthPrice().multiply(cSysCfg.getSyscfgLongValue()).add(ordetailPreLic)) > 0) {
                            map.put("limit",cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "1.0");
                            map.put("SubjectName",subjectName);
                        } else {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "0.0");
                            map.put("SubjectName",subjectName);
                        }
                    } else {
                        if (cOrderDetail.getOrdetailRemainNum().compareTo(cPdtsAuth.getPdtsauthPrice().multiply(cSysCfg.getSyscfgLongValue())) > 0) {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "1.0");
                            map.put("SubjectName",subjectName);
                        } else {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "0.0");
                            map.put("SubjectName",subjectName);
                        }
                    }
                }
            }
            if (Objects.equals(cPdtClass.getPdtclassClass(), "石膏")) {
                QueryWrapper<CSysCfg> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("SYSCFG_ITEM_NAME", "RemainLimit_Gypsum");
                queryWrapper4.eq("DATA_FROM", plant);
                CSysCfg cSysCfg = iCSysCfgService.getOne(queryWrapper4);
                if (Double.parseDouble(cSysCfg.getSyscfgLongValue().toString()) > 0) {
                    QueryWrapper<CPdtsAuth> queryWrapper5 = new QueryWrapper<>();
                    queryWrapper5.eq("PDTSAUTH_CO", co);
                    queryWrapper5.eq("PDTSAUTH_CHICO", chiCo);
                    queryWrapper5.eq("PDTSAUTH_DELETED", 0);
                    queryWrapper5.eq("PDTSAUTH_PDT", cardinfTruckTypeValue);
                    CPdtsAuth cPdtsAuth = iCPdtsAuthService.getOne(queryWrapper5);
//            如果cSysCfg的值不为0就判断cSysCfg的值乘以cPdtsAuth里的价格判断是否大于余额,如果if (Integer.parseInt(cSysCfg1.getSyscfgLongValue().toString()) == 1) 就判断是否大于余额加上授信额度
                    if (CreditLineEn) {
                        if (cOrderDetail.getOrdetailRemainNum().compareTo(cPdtsAuth.getPdtsauthPrice().multiply(cSysCfg.getSyscfgLongValue()).add(ordetailPreLic)) > 0) {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "1.0");
                            map.put("SubjectName",subjectName);
                        } else {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "0.0");
                            map.put("SubjectName",subjectName);
                        }
                    } else {
                        if (cOrderDetail.getOrdetailRemainNum().compareTo(cPdtsAuth.getPdtsauthPrice().multiply(cSysCfg.getSyscfgLongValue())) > 0) {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "1.0");
                            map.put("SubjectName",subjectName);
                        } else {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "0.0");
                            map.put("SubjectName",subjectName);
                        }
                    }
                }
            }
            if (cPdtClass.getPdtclassClass().contains("渣")) {
                QueryWrapper<CSysCfg> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("SYSCFG_ITEM_NAME", "RemainLimit_Cinder");
                queryWrapper4.eq("DATA_FROM", plant);
                CSysCfg cSysCfg = iCSysCfgService.getOne(queryWrapper4);
                if (Integer.parseInt(cSysCfg.getSyscfgLongValue().toString()) > 0) {
                    QueryWrapper<CPdtsAuth> queryWrapper5 = new QueryWrapper<>();
                    queryWrapper5.eq("PDTSAUTH_CO", co);
                    queryWrapper5.eq("PDTSAUTH_CHICO", chiCo);
                    queryWrapper5.eq("PDTSAUTH_DELETED", 0);
                    queryWrapper5.eq("PDTSAUTH_PDT", cardinfTruckTypeValue);
                    CPdtsAuth cPdtsAuth = iCPdtsAuthService.getOne(queryWrapper5);
//            如果cSysCfg的值不为0就判断cSysCfg的值乘以cPdtsAuth里的价格判断是否大于余额,如果if (Integer.parseInt(cSysCfg1.getSyscfgLongValue().toString()) == 1) 就判断是否大于余额加上授信额度
                    if (CreditLineEn) {
                        if (cOrderDetail.getOrdetailRemainNum().compareTo(cPdtsAuth.getPdtsauthPrice().multiply(cSysCfg.getSyscfgLongValue()).add(ordetailPreLic)) > 0) {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "1.0");
                            map.put("SubjectName",subjectName);
                        } else {
                            map.put("limit",cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "0.0");
                            map.put("SubjectName",subjectName);
                        }
                    } else {
                        if (cOrderDetail.getOrdetailRemainNum().compareTo(cPdtsAuth.getPdtsauthPrice().multiply(cSysCfg.getSyscfgLongValue())) > 0) {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "1.0");
                            map.put("SubjectName",subjectName);
                        } else {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "0.0");
                            map.put("SubjectName",subjectName);
                        }
                    }
                }
            }
//        不等于粉煤灰、石膏、渣
            if (!Objects.equals(cPdtClass.getPdtclassClass(), "粉煤灰") && !Objects.equals(cPdtClass.getPdtclassClass(), "石膏") && !cPdtClass.getPdtclassClass().contains("渣")) {
                QueryWrapper<CSysCfg> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("SYSCFG_ITEM_NAME", "RemainLimit");
                queryWrapper4.eq("DATA_FROM", plant);
                CSysCfg cSysCfg = iCSysCfgService.getOne(queryWrapper4);
                if (Integer.parseInt(cSysCfg.getSyscfgLongValue().toString()) > 0) {

                    QueryWrapper<CPdtsAuth> queryWrapper5 = new QueryWrapper<>();
                    queryWrapper5.eq("PDTSAUTH_CO", co);
                    queryWrapper5.eq("PDTSAUTH_CHICO", chiCo);
                    queryWrapper5.eq("PDTSAUTH_DELETED", 0);
                    queryWrapper5.eq("PDTSAUTH_PDT", cardinfTruckTypeValue);
                    CPdtsAuth cPdtsAuth = iCPdtsAuthService.getOne(queryWrapper5);
//            如果cSysCfg的值不为0就判断cSysCfg的值乘以cPdtsAuth里的价格判断是否大于余额,如果if (Integer.parseInt(cSysCfg1.getSyscfgLongValue().toString()) == 1) 就判断是否大于余额加上授信额度
                    if (CreditLineEn) {

                        if (cOrderDetail.getOrdetailRemainNum().compareTo(cPdtsAuth.getPdtsauthPrice().multiply(cSysCfg.getSyscfgLongValue()).add(ordetailPreLic)) > 0) {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "1.0");
                            map.put("SubjectName",subjectName);
                        } else {
                            map.put("limit",cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "0.0");
                            map.put("SubjectName",subjectName);
                        }
                    } else {
                        if (cOrderDetail.getOrdetailRemainNum().compareTo(cPdtsAuth.getPdtsauthPrice().multiply(cSysCfg.getSyscfgLongValue())) > 0) {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "1.0");
                            map.put("SubjectName",subjectName);
                        } else {
                            map.put("limit", cSysCfg.getSyscfgLongValue().toString());
                            map.put("ok", "0.0");
                            map.put("SubjectName",subjectName);
                        }
                    }
                }
            }
        }
        return map;
    }

    //这个品种是否开启发货计划，计划是否充足
    public boolean isPlan(String plant, String co, String chiCo,String cardinfTruckTypeValue, String cardinfTruckPwd) {
        boolean b = false;
        //        先判断品种是否开启计划控制
        QueryWrapper<CProductsInfo> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("PDTINF_PDT", cardinfTruckTypeValue);
        queryWrapper5.eq("PDTINF_DELETED", 0);
        queryWrapper5.eq("DATA_FROM", plant);
        CProductsInfo cProductsInfo1 = iCProductsInfoService.getOne(queryWrapper5);
        if (cProductsInfo1.getPdtinfPlanCtrl() == null || Integer.parseInt(cProductsInfo1.getPdtinfPlanCtrl().toString()) == 0) {
            return true;
        }
        QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("CPY_CO", co);
        queryWrapper1.eq("CPY_CHICO", chiCo);
        queryWrapper1.eq("CPY_DELETED", 0);
        queryWrapper1.eq("DATA_FROM", plant);
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper1);
        QueryWrapper<CProductsInfo> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("PDTINF_PDT", cardinfTruckTypeValue);
        queryWrapper3.eq("PDTINF_DELETED", 0);
        queryWrapper3.eq("DATA_FROM", plant);
        CProductsInfo cProductsInfo = iCProductsInfoService.getOne(queryWrapper3);
        LocalDateTime now = LocalDateTime.now();
//        查询计划
        QueryWrapper<CPdtPlanEx> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("PDT_PLANEX_COID", cCompanys.getCpyId());
        queryWrapper2.eq("PDT_PLANEX_DELETED", 0);
        queryWrapper2.eq("PDT_PLANEX_PDTID", cProductsInfo.getPdtinfId());
// 大于PDT_PLANEX_BEGIN，小于PDT_PLANEX_END
        queryWrapper2.le("PDT_PLANEX_BEGIN", now);
        queryWrapper2.ge("PDT_PLANEX_END", now);
        queryWrapper2.eq("DATA_FROM", plant);
        CPdtPlanEx cPdtPlanEx = iCPdtPlanExService.getOne(queryWrapper2);
        if (cPdtPlanEx == null) {
            return false;
        }
        QueryWrapper<CWeightSheets> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("WEISHT_CO", cCompanys.getCpyCo());
        queryWrapper4.eq("WEISHT_CHI_CO", cCompanys.getCpyChico());
        queryWrapper4.eq("WEISHT_PRODUCT", cardinfTruckTypeValue);
        queryWrapper4.eq("WEISHT_DELETED", 0);
        queryWrapper4.eq("DATA_FROM", plant);
//       WEISHT_FULL_TM在cPdtPlanEx的开始和结束之间
        queryWrapper4.ge("WEISHT_FULL_TM", cPdtPlanEx.getPdtPlanexBegin());
        queryWrapper4.le("WEISHT_FULL_TM", cPdtPlanEx.getPdtPlanexEnd());
        List<CWeightSheets> cWeightSheets = iCWeightSheetsService.list(queryWrapper4);
//计算一下装了多少吨
        BigDecimal bigDecimal = new BigDecimal(0);
        if (cWeightSheets != null && cWeightSheets.size() > 0) {
            for (CWeightSheets cWeightSheet : cWeightSheets) {
                bigDecimal = bigDecimal.add(cWeightSheet.getWeishtNetWght());
            }
        }
//        预扣了多少吨
        BigDecimal preLic = new BigDecimal(0);
        QueryWrapper<CTrucks> trucksQueryWrapper = new QueryWrapper<>();
        trucksQueryWrapper.eq("TRUCKS_CHECKIN_CO", cCompanys.getCpyId());
        trucksQueryWrapper.eq("TRUCKS_CHECKIN_PDT", cProductsInfo1.getPdtinfId());
        trucksQueryWrapper.ne("TRUCKS_QUEUE_STATUS", 0);
        trucksQueryWrapper.eq("TRUCKS_DELETED", 0);
        trucksQueryWrapper.eq("DATA_FROM", plant);
        List<CTrucks> cTrucks = iCTrucksService.list(trucksQueryWrapper);
        if (cTrucks != null) {
            for (CTrucks cTruck : cTrucks) {
                if (cTruck.getTrucksPreDeduct() != null && cTruck.getTrucksPreDeduct().compareTo(BigDecimal.ZERO) > 0)
                    preLic = preLic.add(cTruck.getTrucksPreDeduct());
            }

        }
//        已经装了多少车
        BigDecimal bigDecimal1 = new BigDecimal(0);
        if (cTrucks != null) {
            bigDecimal1 = bigDecimal1.add(BigDecimal.valueOf(cTrucks.size()));
        }
//        已经排队了多少车
        BigDecimal preLic1 = new BigDecimal(0);
        if (cWeightSheets != null) {
            preLic1 = preLic1.add(BigDecimal.valueOf(cWeightSheets.size()));
        }
//        1车数，2数量
        if (cPdtPlanEx.getPdtPlanexType() == 1) {
//         cPdtPlanEx的PDT_PLANEX_NUM大于cWeightSheets的size加cTrucks的size
            if (cPdtPlanEx.getPdtPlanexNum().compareTo(bigDecimal1.add(preLic1)) > 0) {
                b = true;
            }
        } else {
            BigDecimal remainingValue = cPdtPlanEx.getPdtPlanexNum().subtract(bigDecimal.add(preLic));
            //         cPdtPlanEx的PDT_PLANEX_NUM大以cWeightSheets的size加cTrucks的size
            if (Double.parseDouble(String.valueOf(remainingValue)) > 0) {
                b = true;
            }
//            计划剩余下限
            QueryWrapper<CSysCfg> cSysCfgQueryWrapper1 = new QueryWrapper<>();
            cSysCfgQueryWrapper1.eq("SYSCFG_ITEM_NAME", "PlanRemainLimit");
            cSysCfgQueryWrapper1.eq("DATA_FROM", plant);
            CSysCfg cSysCfg1 = iCSysCfgService.getOne(cSysCfgQueryWrapper1);
//        如果remainingValue小于cSysCfg1的值
            if (remainingValue.multiply(new BigDecimal("1000")).compareTo(cSysCfg1.getSyscfgLongValue()) < 0) {
                return false;
            }
//            计划剩余整车净重比下限
            QueryWrapper<CSysCfg> cSysCfgQueryWrapper = new QueryWrapper<>();
            cSysCfgQueryWrapper.eq("SYSCFG_ITEM_NAME", "PlanRemainWholePct");
            cSysCfgQueryWrapper.eq("DATA_FROM", plant);
            CSysCfg cSysCfg = iCSysCfgService.getOne(cSysCfgQueryWrapper);
//            查这个cardinfTruckPwd车号的最近3次的装载记录，然后计算WEISHT_NET_WGHT的平均重量
            QueryWrapper<CWeightSheets> eightSheetsQueryWrapper = new QueryWrapper<>();
            eightSheetsQueryWrapper.eq("WEISHT_TRUCKNO", cardinfTruckPwd);
            eightSheetsQueryWrapper.eq("WEISHT_DELETED", 0);
            eightSheetsQueryWrapper.ne("WEISHT_NET_WGHT", 0);
            eightSheetsQueryWrapper.eq("DATA_FROM", plant);
            eightSheetsQueryWrapper.orderByDesc("WEISHT_FULL_TM");
            eightSheetsQueryWrapper.last("limit 3");
            List<CWeightSheets> eightSheets = iCWeightSheetsService.list(eightSheetsQueryWrapper);
            BigDecimal netWght = new BigDecimal(0);
            if (eightSheets == null) {
                QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
                cTrucksQueryWrapper.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
                cTrucksQueryWrapper.eq("TRUCKS_DELETED", 0);
                cTrucksQueryWrapper.eq("DATA_FROM", plant);
                CTrucks cTrucks2 = iCTrucksService.getOne(cTrucksQueryWrapper);
                if (cTrucks2 != null) {
                    netWght = netWght.add(cTrucks2.getTrucksRefNet());
                } else {
                    //            系统默认的参考净重
                    QueryWrapper<CSysCfg> cSysCfgQueryWrapper2 = new QueryWrapper<>();
                    cSysCfgQueryWrapper2.eq("SYSCFG_ITEM_NAME", "TempTruckDefRefNet");
                    cSysCfgQueryWrapper2.eq("DATA_FROM", plant);
                    CSysCfg cSysCfg2 = iCSysCfgService.getOne(cSysCfgQueryWrapper2);
                    netWght = netWght.add(cSysCfg2.getSyscfgLongValue());
                }
            } else {
                for (CWeightSheets cWeightSheet : eightSheets) {
                    netWght = netWght.add(cWeightSheet.getWeishtNetWght());
                }
                netWght = netWght.divide(new BigDecimal(eightSheets.size()), 2, RoundingMode.HALF_UP);
            }

//           netWght要乘以cSysCfg的值除以100的值是否大于计划量
            if (remainingValue.compareTo(netWght.multiply(cSysCfg.getSyscfgLongValue()).divide(new BigDecimal(100), RoundingMode.CEILING)) < 0) {
                return false;
            }

////CalcComplByMonths
//            QueryWrapper<CSysCfg> cSysCfgQueryWrapper2 = new QueryWrapper<>();
//            cSysCfgQueryWrapper2.eq("SYSCFG_ITEM_NAME", "CalcComplByMonths");
//            cSysCfgQueryWrapper2.eq("DATA_FROM", plant);
//            CSysCfg cSysCfg2 = iCSysCfgService.getOne(cSysCfgQueryWrapper2);
        }
        return b;
    }

    //这个品种是否开启发货计划，计划是否充足
    public boolean isPlanByPdtId(String plant, String co, String chiCo,String cardinfTruckTypeValue, String cardinfTruckPwd) {
        boolean b = false;
        //        先判断品种是否开启计划控制
        QueryWrapper<CProductsInfo> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("ID", cardinfTruckTypeValue);
        queryWrapper5.eq("PDTINF_DELETED", 0);
        queryWrapper5.eq("DATA_FROM", plant);
        CProductsInfo cProductsInfo1 = iCProductsInfoService.getOne(queryWrapper5);
        if (cProductsInfo1.getPdtinfPlanCtrl() == null || Integer.parseInt(cProductsInfo1.getPdtinfPlanCtrl().toString()) == 0) {
            return true;
        }
        QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("CPY_CO", co);
        queryWrapper1.eq("CPY_CHICO", chiCo);
        queryWrapper1.eq("CPY_DELETED", 0);
        queryWrapper1.eq("DATA_FROM", plant);
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper1);
        QueryWrapper<CProductsInfo> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("ID", cardinfTruckTypeValue);
        queryWrapper3.eq("PDTINF_DELETED", 0);
        queryWrapper3.eq("DATA_FROM", plant);
        CProductsInfo cProductsInfo = iCProductsInfoService.getOne(queryWrapper3);
        LocalDateTime now = LocalDateTime.now();
//        查询计划
        QueryWrapper<CPdtPlanEx> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("PDT_PLANEX_COID", cCompanys.getCpyId());
        queryWrapper2.eq("PDT_PLANEX_DELETED", 0);
        queryWrapper2.eq("PDT_PLANEX_PDTID", cProductsInfo.getPdtinfId());
// 大于PDT_PLANEX_BEGIN，小于PDT_PLANEX_END
        queryWrapper2.le("PDT_PLANEX_BEGIN", now);
        queryWrapper2.ge("PDT_PLANEX_END", now);
        queryWrapper2.eq("DATA_FROM", plant);
        CPdtPlanEx cPdtPlanEx = iCPdtPlanExService.getOne(queryWrapper2);
        if (cPdtPlanEx == null) {
            return false;
        }
        QueryWrapper<CWeightSheets> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("WEISHT_CO", cCompanys.getCpyCo());
        queryWrapper4.eq("WEISHT_CHI_CO", cCompanys.getCpyChico());
        queryWrapper4.eq("WEISHT_PRODUCT", cProductsInfo.getPdtinfPdt());
        queryWrapper4.eq("WEISHT_DELETED", 0);
        queryWrapper4.eq("DATA_FROM", plant);
//       WEISHT_FULL_TM在cPdtPlanEx的开始和结束之间
        queryWrapper4.ge("WEISHT_FULL_TM", cPdtPlanEx.getPdtPlanexBegin());
        queryWrapper4.le("WEISHT_FULL_TM", cPdtPlanEx.getPdtPlanexEnd());
        List<CWeightSheets> cWeightSheets = iCWeightSheetsService.list(queryWrapper4);
//计算一下装了多少吨
        BigDecimal bigDecimal = new BigDecimal(0);
        if (cWeightSheets != null && cWeightSheets.size() > 0) {
            for (CWeightSheets cWeightSheet : cWeightSheets) {
                bigDecimal = bigDecimal.add(cWeightSheet.getWeishtNetWght());
            }
        }
//        预扣了多少吨
        BigDecimal preLic = new BigDecimal(0);
        QueryWrapper<CTrucks> trucksQueryWrapper = new QueryWrapper<>();
        trucksQueryWrapper.eq("TRUCKS_CHECKIN_CO", cCompanys.getCpyId());
        trucksQueryWrapper.eq("TRUCKS_CHECKIN_PDT", cProductsInfo1.getPdtinfId());
        trucksQueryWrapper.ne("TRUCKS_QUEUE_STATUS", 0);
        trucksQueryWrapper.eq("TRUCKS_DELETED", 0);
        trucksQueryWrapper.eq("DATA_FROM", plant);
        List<CTrucks> cTrucks = iCTrucksService.list(trucksQueryWrapper);
        if (cTrucks != null) {
            for (CTrucks cTruck : cTrucks) {
                if (cTruck.getTrucksPreDeduct() != null && cTruck.getTrucksPreDeduct().compareTo(BigDecimal.ZERO) > 0)
                    preLic = preLic.add(cTruck.getTrucksPreDeduct());
            }

        }
//        已经装了多少车
        BigDecimal bigDecimal1 = new BigDecimal(0);
        if (cTrucks != null) {
            bigDecimal1 = bigDecimal1.add(BigDecimal.valueOf(cTrucks.size()));
        }
//        已经排队了多少车
        BigDecimal preLic1 = new BigDecimal(0);
        if (cWeightSheets != null) {
            preLic1 = preLic1.add(BigDecimal.valueOf(cWeightSheets.size()));
        }
//        1车数，2数量
        if (cPdtPlanEx.getPdtPlanexType() == 1) {
//         cPdtPlanEx的PDT_PLANEX_NUM大于cWeightSheets的size加cTrucks的size
            if (cPdtPlanEx.getPdtPlanexNum().compareTo(bigDecimal1.add(preLic1)) > 0) {
                b = true;
            }
        } else {
            BigDecimal remainingValue = cPdtPlanEx.getPdtPlanexNum().subtract(bigDecimal.add(preLic));
            //         cPdtPlanEx的PDT_PLANEX_NUM大以cWeightSheets的size加cTrucks的size
            if (Double.parseDouble(String.valueOf(remainingValue)) > 0) {
                b = true;
            }
//            计划剩余下限
            QueryWrapper<CSysCfg> cSysCfgQueryWrapper1 = new QueryWrapper<>();
            cSysCfgQueryWrapper1.eq("SYSCFG_ITEM_NAME", "PlanRemainLimit");
            cSysCfgQueryWrapper1.eq("DATA_FROM", plant);
            CSysCfg cSysCfg1 = iCSysCfgService.getOne(cSysCfgQueryWrapper1);
//        如果remainingValue小于cSysCfg1的值
            if (remainingValue.multiply(new BigDecimal("1000")).compareTo(cSysCfg1.getSyscfgLongValue()) < 0) {
                return false;
            }
//            计划剩余整车净重比下限
            QueryWrapper<CSysCfg> cSysCfgQueryWrapper = new QueryWrapper<>();
            cSysCfgQueryWrapper.eq("SYSCFG_ITEM_NAME", "PlanRemainWholePct");
            cSysCfgQueryWrapper.eq("DATA_FROM", plant);
            CSysCfg cSysCfg = iCSysCfgService.getOne(cSysCfgQueryWrapper);
//            查这个cardinfTruckPwd车号的最近3次的装载记录，然后计算WEISHT_NET_WGHT的平均重量
            QueryWrapper<CWeightSheets> eightSheetsQueryWrapper = new QueryWrapper<>();
            eightSheetsQueryWrapper.eq("WEISHT_TRUCKNO", cardinfTruckPwd);
            eightSheetsQueryWrapper.eq("WEISHT_DELETED", 0);
            eightSheetsQueryWrapper.ne("WEISHT_NET_WGHT", 0);
            eightSheetsQueryWrapper.eq("DATA_FROM", plant);
            eightSheetsQueryWrapper.orderByDesc("WEISHT_FULL_TM");
            eightSheetsQueryWrapper.last("limit 3");
            List<CWeightSheets> eightSheets = iCWeightSheetsService.list(eightSheetsQueryWrapper);
            BigDecimal netWght = new BigDecimal(0);
            if (eightSheets == null) {
                QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
                cTrucksQueryWrapper.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
                cTrucksQueryWrapper.eq("TRUCKS_DELETED", 0);
                cTrucksQueryWrapper.eq("DATA_FROM", plant);
                CTrucks cTrucks2 = iCTrucksService.getOne(cTrucksQueryWrapper);
                if (cTrucks2 != null) {
                    netWght = netWght.add(cTrucks2.getTrucksRefNet());
                } else {
                    //            系统默认的参考净重
                    QueryWrapper<CSysCfg> cSysCfgQueryWrapper2 = new QueryWrapper<>();
                    cSysCfgQueryWrapper2.eq("SYSCFG_ITEM_NAME", "TempTruckDefRefNet");
                    cSysCfgQueryWrapper2.eq("DATA_FROM", plant);
                    CSysCfg cSysCfg2 = iCSysCfgService.getOne(cSysCfgQueryWrapper2);
                    netWght = netWght.add(cSysCfg2.getSyscfgLongValue());
                }
            } else {
                for (CWeightSheets cWeightSheet : eightSheets) {
                    netWght = netWght.add(cWeightSheet.getWeishtNetWght());
                }
                netWght = netWght.divide(new BigDecimal(eightSheets.size()), 2, RoundingMode.HALF_UP);
            }

//           netWght要乘以cSysCfg的值除以100的值是否大于计划量
            if (remainingValue.compareTo(netWght.multiply(cSysCfg.getSyscfgLongValue()).divide(new BigDecimal(100), RoundingMode.CEILING)) < 0) {
                return false;
            }

////CalcComplByMonths
//            QueryWrapper<CSysCfg> cSysCfgQueryWrapper2 = new QueryWrapper<>();
//            cSysCfgQueryWrapper2.eq("SYSCFG_ITEM_NAME", "CalcComplByMonths");
//            cSysCfgQueryWrapper2.eq("DATA_FROM", plant);
//            CSysCfg cSysCfg2 = iCSysCfgService.getOne(cSysCfgQueryWrapper2);
        }
        return b;
    }

//    石膏渣计划的判断
public Map<String, Object> isPlan2(String coId, String pdtId) {
    // 获取当前日期
    LocalDate today = LocalDate.now();

    // 将 LocalDate 转换为字符串
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    String todayStr = today.format(formatter);

    // 创建查询条件
    QueryWrapper<TGypsumPlan> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("CO_ID", coId);
    queryWrapper.eq("PDT_ID", pdtId);
    queryWrapper.eq("PLAN_TIME", todayStr);  // 使用字符串形式的日期
    queryWrapper.eq("DEL_FLAG", 0);
    // 执行查询
    TGypsumPlan gypsumPlan = iTGypsumPlanService.getOne(queryWrapper);
    // 构建返回结果
    Map<String, Object> result = new HashMap<>();
    if (gypsumPlan != null ) {
        result.put("code", "0");
        result.put("gypsumPlan", gypsumPlan);
    } else {
        result.put("code", "1");
        result.put("gypsumPlan", null);
    }

    return result;
}


    //    直接查当天的石膏计划，石膏计划一天只有一个公司会有
    public Map<String,Object> isPlan3(String day, String pdtId) {
        QueryWrapper<TGypsumPlan> queryWrapper = new QueryWrapper<>();
//        PLAN_TIME是2024-07-31年月日的格式
        queryWrapper.eq("PLAN_TIME", day);
        queryWrapper.eq("PDT_ID", pdtId);
        queryWrapper.eq("PLAN_TIME",LocalDateTime.now().truncatedTo(ChronoUnit.DAYS));
        queryWrapper.eq("DEL_FLAG",0);
        TGypsumPlan gypsumPlan = iTGypsumPlanService.getOne(queryWrapper);
        if (gypsumPlan != null && gypsumPlan.getId()!=null) {
            Map<String,Object> map = new HashMap<>();
            map.put("code","0");
            map.put("gypsumPlan",gypsumPlan);
            return map;
        }else {
            Map<String,Object> map = new HashMap<>();
            map.put("code","1");
            map.put("gypsumPlan",null);
            return map;
        }
    }

    //    扣款的时候按照排队的计划扣款
    public Map<String,Object> isPlan4(LocalDateTime day1,String coId, String pdtId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String day = day1.format(formatter);
        QueryWrapper<TGypsumPlan> queryWrapper = new QueryWrapper<>();
//        PLAN_TIME是2024-07-31年月日的格式
        queryWrapper.eq("PLAN_TIME", day);
        queryWrapper.eq("PDT_ID", pdtId);
        queryWrapper.eq("CO_ID", coId);
        queryWrapper.eq("DEL_FLAG",0);
        TGypsumPlan gypsumPlan = iTGypsumPlanService.getOne(queryWrapper);
        if (gypsumPlan != null && gypsumPlan.getId()!=null) {
            Map<String,Object> map = new HashMap<>();
            map.put("code","0");
            map.put("gypsumPlan",gypsumPlan);
            return map;
        }else {
            Map<String,Object> map = new HashMap<>();
            map.put("code","1");
            map.put("gypsumPlan",null);
            return map;
        }
    }
    //    判断今天石膏计划是公司多还是电厂多，那一二期石膏和三四期石膏就按照这个进行扣款
    public String getTodayPlan(LocalDateTime now) {
        // 把now变成0点0分0秒
        LocalDateTime startOfDay = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
        // 计算当天结束时间（即第二天的0点0分0秒）
        LocalDateTime endOfDay = startOfDay.plusDays(1);

        QueryWrapper<TGypsumPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("PLAN_TIME", startOfDay, endOfDay);

        List<TGypsumPlan> list = iTGypsumPlanService.list(queryWrapper);
        if (list == null || list.isEmpty()) {
            return null;
        }

        // 统计每个 CO_ID 的出现次数
        Map<String, Long> coIdCounts = list.stream()
                .collect(Collectors.groupingBy(TGypsumPlan::getCoId, Collectors.counting()));

        // 找出出现次数最多的 CO_ID
        return coIdCounts.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElseGet(() -> list.get(0).getCoId());
    }


    // 用于跟踪当前石膏阶段的计数器，并直接初始化
    private int callCount = 0;

    /**
     * 获取当前石膏阶段的信息，并更新计数器。
     * @return 返回当前石膏阶段的字符串描述。
     */
    public int getShigaoAshGate() {
        // 更新计数器，并将其限制在 0 到 2 之间
        callCount = (callCount + 1) % 3;

        if (callCount == 0) {
            // 第一次调用
            return 26;
        } else {
            // 第二次和第三次调用
            return 27;
        }
    }

    // 用于跟踪当前渣仓编号的计数器，并直接初始化
    private int callCount1 = 0;

    // 渣仓编号数组
    private static final int[] ASH_BINS = {37, 35, 38, 33};
    /**
     * 获取当前渣仓编号的信息，并更新计数器。
     * @return 返回当前渣仓编号的字符串描述。
     */
    public int getZhaAshGate() {
        // 更新计数器，并将其限制在 0 到 ASH_BINS.length - 1 之间
        callCount1 = (callCount1 + 1) % ASH_BINS.length;
        // 计算当前应该返回哪个渣仓编号
        return ASH_BINS[callCount1];
    }
}
